<?php
namespace app\index;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use think\Log;

class Mywebsocket implements MessageComponentInterface {
    protected $clients;

    public function onOpen(ConnectionInterface $conn) {
        
        $this->clients = $conn;
        // 新连接时会调用
        $this->clients->send("返回链接成功的信息");
        print('server is starting ....');
        // log("onOpen");
        // Log::record("open", "error");
    }
 
    public function onMessage(ConnectionInterface $from, $msg) {
        // Log::record("onMessage");

        $this->clients->send($msg);

        // Log::record($this->clients);
        
        // // 收到消息时调用
        // foreach ($this->clients as $client) {
        //     if ($from !== $client) {
        //         $client->send($msg);
        //     }
        // }
    }

    public function getClient(){
        return $this->clients;
    }
 
    public function onClose(ConnectionInterface $conn) {
        // 连接关闭时调用
        log::record("onClose");

    }
 
    public function onError(ConnectionInterface $conn, \Exception $e) {
        log::record("onError");
        // 发生错误时调用
        $conn->close();
    }
}